package OThinker.H3.Portal.webservices.impl;


import OThinker.Common.Organization.Models.User;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Portal.webservices.U8SampleService;

import com.h3bpm.base.config.PortalPropertiesUtil;

import com.h3bpm.base.util.AppUtility;
import com.h3bpm.kumhosunny.common.utils.SqlUtil;
import data.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.jws.WebService;
import javax.xml.ws.Endpoint;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


/**
 * @authormi @date2019/6/24
 */
@WebService(targetNamespace = "http://U8SampleService/")
public class U8SampleServiceImpl implements U8SampleService {

    private final static Logger LOGGER = LoggerFactory.getLogger(U8SampleServiceImpl.class);

    public static Endpoint startService(){
        U8SampleServiceImpl u8SampleServiceImpl = new U8SampleServiceImpl();
        String address= PortalPropertiesUtil.getProperty("U8SampleServiceAddress");

        try {
            InetAddress ia = InetAddress.getLocalHost();
            address = address.replace("127.0.0.1", ia.getHostAddress());
            LOGGER.info(">> u8SampleServiceAddress: " + address);
        } catch (UnknownHostException e) {
            LOGGER.error(">> ", e);
        }

        return Endpoint.publish(address, u8SampleServiceImpl);
    }


    /**
     * 样品开发U8状态写入接口
     * @param itemNumber
     * @param applicationNo
     * @param statesName
     * @param instentsId
     * @return
     */
    @Override
    public int writeSampleProcessSataus(String itemNumber, String applicationNo, String statesName, String instentsId) {

        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String createBy = "";
            String createTime = simpleDateFormat.format(new Date());
        if(instentsId!=null && !"".equals(instentsId)) {
                InstanceData instanceData = new InstanceData(AppUtility.getEngine(),instentsId, User.AdministratorID);
                instanceData.getBizObject().setItem("procesState",statesName);
                instanceData.getBizObject().setItem("processStarTime",createTime);
                instanceData.Submit();
                  itemNumber ="";
                  applicationNo ="";
                if(instanceData.getBizObject().getItem("itemNo")!=null){
                    itemNumber =instanceData.getBizObject().getItem("itemNo").toString();
                }
                if(instanceData.getBizObject().getItem("applicationNo")!=null){
                    applicationNo =instanceData.getBizObject().getItem("applicationNo").toString();
                }
            createBy= instanceData.getInstanceContext().getOriginator();
        }else{
          String getInstanceIdSql =   "select b.ObjectID from i_sampleApplication a inner join ot_instancecontext b on a.ObjectID=b.BizObjectId where a.itemNo='"+itemNumber+"' and a.applicationNo='"+applicationNo+"'";
          DataTable dataTable  = SqlUtil.doQuery(getInstanceIdSql);
            if(dataTable!=null && dataTable.getEntityRows()!=null && dataTable.getEntityRows().size()>0) {
                instentsId = dataTable.getEntityRows().get(0).getString("ObjectID");
                InstanceData instanceData = new InstanceData(AppUtility.getEngine(), instentsId, User.AdministratorID);
                instanceData.getBizObject().setItem("procesState", statesName);
                instanceData.getBizObject().setItem("processStarTime",createTime);
                instanceData.Submit();
                itemNumber = "";
                applicationNo = "";
                if (instanceData.getBizObject().getItem("itemNo") != null) {
                    itemNumber = instanceData.getBizObject().getItem("itemNo").toString();
                }
                if (instanceData.getBizObject().getItem("applicationNo") != null) {
                    applicationNo = instanceData.getBizObject().getItem("applicationNo").toString();
                }
                createBy= instanceData.getInstanceContext().getOriginator();
            }
        }

        String getLastTimeSql =  "select ObjectId from k_samplestate where itemNumber = '"+itemNumber+"' and applicationNo = '"+applicationNo+"' order by  CreatedTime desc";
        DataTable dataTable = SqlUtil.doQuery(getLastTimeSql);
        String lastObjectId = "";
        if(dataTable!=null && dataTable.getEntityRows()!=null && dataTable.getEntityRows().size()>0){
            lastObjectId =  dataTable.getEntityRows().get(0).getString("ObjectId");
            String updateU8State = "update k_samplestate set ModifiedTime = '"+createTime+"' where  ObjectId= '"+lastObjectId+"'";
            SqlUtil.doNoQuery(updateU8State);
        }
        String insertU8State = "insert into k_samplestate ( itemNumber,statesName,instentsId,ObjectId,CreatedTime,CreatedBy,ModifiedTime,ModifiedBy,applicationNo)";
            String objectId = UUID.randomUUID().toString();
            insertU8State=insertU8State+" values ('"+itemNumber+"','"+statesName+"','"+instentsId+"','"+objectId+"','"+createTime+"','"+createBy+"','"+createTime+"','"+createBy+"','"+applicationNo+"')";
            SqlUtil.doNoQuery(insertU8State);
        } catch (Exception e) {
            e.printStackTrace();
            return 500;
        }
        return 200;
    }


    @Override
    public int writeSampleMark(String itemNumber, String applicationNo,String actualNumber ,String actualColor,
                               String custom1 ,String custom2 ,String additionalSampleRequired,
                               String additionalRequiredSwatches,String extraSample,String realMember){

       try {
           String getInstanceIdSql =   "select b.ObjectID from i_sampleApplication a inner join ot_instancecontext b on a.ObjectID=b.BizObjectId where a.itemNo='"+itemNumber+"' and a.applicationNo='"+applicationNo+"'";
           DataTable dataTable  = SqlUtil.doQuery(getInstanceIdSql);
           if(dataTable!=null && dataTable.getEntityRows()!=null && dataTable.getEntityRows().size()>0) {
              String instentsId = dataTable.getEntityRows().get(0).getString("ObjectID");
               InstanceData instanceData = new InstanceData(AppUtility.getEngine(), instentsId, User.AdministratorID);
              if(actualNumber!=null) {
                  instanceData.getBizObject().setItem("actualNumber", actualNumber);
              }
               if(actualColor!=null) {
                   instanceData.getBizObject().setItem("actualColor", actualColor);
               }
               if(custom1!=null) {
                   instanceData.getBizObject().setItem("custom1", custom1);
               }
               if(custom2!=null) {
                   instanceData.getBizObject().setItem("custom2", custom2);
               }
               //额外需要的样料(kg)
               if(additionalSampleRequired!=null) {
                   instanceData.getBizObject().setItem("additionalSampleRequired", additionalSampleRequired);
               }
               if(additionalRequiredSwatches!=null) {
                   instanceData.getBizObject().setItem("additionalRequiredSwatches", additionalRequiredSwatches);
               }
               if(extraSample!=null){
                   instanceData.getBizObject().setItem("extraSample",extraSample);
               }
               //实际研发员
               if(realMember!=null){
                   instanceData.getBizObject().setItem("rdmember",realMember);
               }

               instanceData.Submit();
           }
        } catch (Exception e) {
            e.printStackTrace();
            return 500;
        }
         return 200;
    }

    @Override
    public int writeSampleInternalSummary(String problemDescription, String overviewReason, String countermeasures, String classification, String failureProcess, String failureType, String countermeasuresCategory, String feedbackInstanceId, String itemNumber, String applicationNo) {

        try {
            if(feedbackInstanceId!=null && !"".equals(feedbackInstanceId)) {
                InstanceData instanceData = new InstanceData(AppUtility.getEngine(),feedbackInstanceId, User.AdministratorID);
                instanceData.getBizObject().setItem("problemDescription",problemDescription);
                instanceData.getBizObject().setItem("overviewReason",overviewReason);
                instanceData.getBizObject().setItem("countermeasures",countermeasures);
                instanceData.getBizObject().setItem("classification",classification);
                instanceData.getBizObject().setItem("failureProcess",failureProcess);
                instanceData.getBizObject().setItem("failureType",failureType);
                instanceData.getBizObject().setItem("countermeasuresCategory",countermeasuresCategory);
                instanceData.Submit();

            }else{
                String getInstanceIdSql =   "select b.ObjectID from i_customerFeedbackSheet a inner join ot_instancecontext b on a.ObjectID=b.BizObjectId where a.itemNo='"+itemNumber+"' and a.applicationNo='"+applicationNo+"'";
                DataTable dataTable  = SqlUtil.doQuery(getInstanceIdSql);
                if(dataTable!=null && dataTable.getEntityRows()!=null && dataTable.getEntityRows().size()>0) {
                    feedbackInstanceId = dataTable.getEntityRows().get(0).getString("ObjectID");
                    InstanceData instanceData = new InstanceData(AppUtility.getEngine(),feedbackInstanceId, User.AdministratorID);
                    instanceData.getBizObject().setItem("problemDescription",problemDescription);
                    instanceData.getBizObject().setItem("overviewReason",overviewReason);
                    instanceData.getBizObject().setItem("countermeasures",countermeasures);
                    instanceData.getBizObject().setItem("classification",classification);
                    instanceData.getBizObject().setItem("failureProcess",failureProcess);
                    instanceData.getBizObject().setItem("failureType",failureType);
                    instanceData.getBizObject().setItem("countermeasuresCategory",countermeasuresCategory);
                    instanceData.Submit();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return 500;
        }
        return 200;
    }
}
